import $ from '../common'
import WeCropper from './we-cropper.js'

Page({
	data: {
		moveStatus: false
	},
	touchStart(e) {
		clearTimeout(this.data.moveTime)
		this.data.moveStatus = false
		this.wecropper.touchStart(e)
	},
	touchMove(e) {
		if(!this.data.moveStatus) {
			this.data.moveStatus = true
			this.data.moveTime = setTimeout(() => {
				this.wecropper.touchMove(e)
				this.data.moveStatus = false
			}, 10)
		}
	},
	touchEnd(e) {
		this.wecropper.touchEnd(e)
	},
	getCropperImage() {
		wx.showLoading()
		this.wecropper.getCropperImage((src) => {
			if(src) {
				$.upload("/image/upload/oss", {
					filePaths: src,
					prefix: this.data.prefix
				}, (data) => {
					wx.hideLoading()
					$.parent()._$chooseImage(data[0])
					wx.navigateBack()
				})
			} else {
				wx.hideLoading()
				console.log('获取图片地址失败，请稍后重试')
			}
		})
	},
	uploadTap() {
		const self = this
		wx.chooseImage({
			count: 1,
			sizeType: ['compressed'],
			success(res) {
				const src = res.tempFilePaths[0]
				self.wecropper.pushOrign(src)
			}
		})
	},
	onLoad(option) {

		const device = $.device
		const width = device.windowWidth
		const height = device.windowHeight - 130
		const ratio = option.ratio || 1

		let $width = 300
		let $height = 300
		if(ratio != 1) {
			$width = width
			$height = parseInt(width / ratio)
		}

		this.data.cropperOpt = {
			id: 'cropper',
			width,
			height,
			scale: 2.5,
			zoom: 8,
			cut: {
				x: (width - $width) / 2,
				y: (height - $height) / 2,
				width: $width,
				height: $height
			}
		}

		this.setData({
			cropperOpt: this.data.cropperOpt
		})

		this.data.prefix = option.prefix || "user/avatar/"
		new WeCropper(this.data.cropperOpt)
			.on('ready', (ctx) => {
				if(option.src) {
					this.wecropper.pushOrign(unescape(option.src))
				}
			})
			.on('beforeImageLoad', (ctx) => {
				wx.showToast({
					title: '上传中',
					icon: 'loading',
					duration: 20000
				})
			})
			.on('imageLoad', (ctx) => {
				wx.hideToast()
			})
			.on('beforeDraw', (ctx, instance) => {
				//
			})
			.updateCanvas()
	},
	onUnload() {
		wx.setStorageSync('_$chooseImageRatio', '')
	}
})